package com.robot.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.robot.dao.dto.StatsDTO;
import com.robot.dao.entity.ChatHistory;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import org.apache.ibatis.annotations.Param;
import java.util.List;

@Mapper
@Repository
public interface ChatMapper extends BaseMapper<ChatHistory> {

    @Select("select * from chat_history where robot_id = #{chatHistory.robotId} and user_id = #{chatHistory.userId} order by create_time desc limit #{chatHistoryNumber}")
    List<ChatHistory> queryByUserIdAndRobotId(ChatHistory chatHistory, Integer chatHistoryNumber);

    @Select("select COUNT(*) from chat_history where user_id = #{userId} and create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)")
    Integer countChatHistoryByUserId(StatsDTO statsDTO);

    @Select("select COUNT(*) from chat_history where robot_id = #{robotId} and user_id=#{userId} and create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)")
    Long countChatHistoryByRobotIdAnduserId(@Param("robotId") Long robotId,@Param("userId") Long userId);


    @Select("select COUNT(*) from chat_history where robot_id = #{robotId} ")
    Long countChatHistoryByRobotId(@Param("robotId") Long robotId);

    @Select("SELECT COUNT(DISTINCT user_id) FROM chat_history " +
            "WHERE robot_id = #{robotId} " )
    Integer countDistinctUsersByRobotId(@Param("robotId") String robotId);


    void create(ChatHistory chatHistory);

    @Select("<script>" +
            "SELECT COUNT(*) FROM chat_history " +
            "WHERE user_id IN " +
            "<foreach item='userId' collection='userIds' open='(' separator=',' close=')'>" +
            "#{userId}" +
            "</foreach>" +
            "AND create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)" +
            "</script>")
    Integer countChatHistoryByUserIds(@Param("userIds") List<String> userIds);

    @Select("<script>" +
            "SELECT COUNT(DISTINCT user_id) FROM chat_history " +
            "WHERE user_id IN " +
            "<foreach item='userId' collection='userIds' open='(' separator=',' close=')'>" +
            "#{userId}" +
            "</foreach>" +
            "AND create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)" +
            "</script>")
    Integer countDistinctUsersByUserIds(@Param("userIds") List<String> userIds);


}
